package com.fuluwa.interfaces.product.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fuluwa.domain.product.service.FacetQueryService;
import com.fuluwa.domain.product.service.FacetResult;
import com.fuluwa.infra.web.AbstractDomainController;
import com.fuluwa.infra.web.Result;
import com.fuluwa.interfaces.product.facade.ProductDTO;
import com.fuluwa.interfaces.product.facade.ProductServiceFacade;

@Controller
@RequestMapping(value = "/admin/product")
public class ProductConctroller extends AbstractDomainController {
	@Autowired
	ProductServiceFacade productServiceFacade;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index(Model model) {
		model.addAttribute("cagetory", productServiceFacade.findByLevel(2));
		return "../admin/product.jsp";
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Result add(@RequestBody ProductDTO productDTO) {
		logger.debug("request add(POST):" + productDTO);
		try {
			productServiceFacade.saveProduct(productDTO);
		} catch (Exception e) {
			logger.error("error", e);
			return getFailResult("User Register Failed:" + e.getMessage());
		}
		return getSuccessResult();
	}

	@RequestMapping(value = "search", method = RequestMethod.GET)
	@ResponseBody
	public Result search(@RequestParam String q, @RequestParam String fq) {
		logger.debug("request search(GET):" + q + "," + fq);
		try {
			FacetResult result = new FacetQueryService().facetQuery(q, fq);
			return getSuccessResult(result);
		} catch (Exception e) {
			logger.error("error", e);
			return getFailResult("User Register Failed:" + e.getMessage());
		}
	}
}
